
import { ref, reactive, onMounted, defineComponent, toRefs, nextTick, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import roleApi from '@/api/system/role-api'
import menuApi from '@/api/system/menu-api'
import ZlrtTable from '@/components/zlrt-table/table.vue'
import ZlrtSearch from '@/components/zlrt-search/search.vue'
import TableContext from '@/components/zlrt-table/table-context'
import * as _ from 'lodash';

export default defineComponent({
  components: {
    ZlrtTable,
    ZlrtSearch
  },
  setup() {
    const disabledOptions = [
      { label: '正常', value: false },
      { label: '停用', value: true }
    ]

    const ctx = reactive(new TableContext(getCurrentInstance(), {
      title: '角色',
      api: roleApi,
      columns: [
        { prop: 'roleName', label: '角色名称', valueType: 'input' },
        { prop: 'roleKey', label: '权限字符', valueType: 'input' },
        { prop: 'disabled', label: '状态', slot: true, valueType: 'select', options: disabledOptions, permit: ['core:role:save'] },
        { prop: 'operation', label: '操作', slot: true }
      ],
      // 表单校验项规则
      rules: {
        roleName: [{ required: true, message: '请输入角色名称', trigger: 'blur' }],
        roleKey: [{ required: true, message: '请输入权限字符', trigger: 'blur' }],
        disabled: [{ required: true, message: '请选择状态', trigger: 'change' }]
      },
      other: {
        // 状态切换
        statusChanged: (row) => {
          const { roleName, disabled } = row
          ElMessageBox.confirm(`确认要${disabled ? '停用' : '启用'}"${roleName}"${ctx.title}吗？`, '温馨提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            draggable: true
          })
            .then(async () => {
              const res = await roleApi.save(row)
              if (res.code === 200) {
                ElMessage.success(`${disabled ? '停用' : '启用'}成功`)
              } else {
                row.disabled = !disabled
              }
            })
            .catch(() => {
              row.disabled = !disabled
            })
        }
      }
    }))

    //权限
    const pctx = reactive(new TableContext(getCurrentInstance(), {
      title: '角色权限',
      showEdit: async (row) => {
        pctx.other.id = row.id;
        pctx.data = [];
        pctx.editVisible = true;
        const res = await roleApi.getMenus(row.id);
        pctx.data = _.cloneDeep(pctx.other.data);
        if (res.success) {
          const roles = res.data || [];
          const checkedIds = roles
            .filter(o => !roles.some(x => x.parentId == o.id))
            .map(o => o.id)
          pctx.other.tree.setCheckedKeys(checkedIds);
        }
      },
      loadData: async () => {
        const res = await menuApi.list({
          filter: {
            disabled: false,
          },
          size: 5000,
        })
        if (res.success) {
          pctx.other.data = res.data?.records || []
          pctx.other.data = treeBuild(pctx.other.data);
        }

      },
      save: async (row) => {
        const menus = pctx.other.tree.getCheckedKeys()
          .concat(pctx.other.tree.getHalfCheckedKeys());
        const res = await roleApi.setMenus(pctx.other.id, menus);
        if (res.success) {
          pctx.editVisible = false;
        }
      },
      other: {
        props: {
          label: 'menuName',
          children: 'children'
        },

      }
    }));

    const treeBuild: any = (data, parent) => {
      if (!data) {
        return;
      }
      parent = parent ?? data.filter(o => !data.some(x => x.id == o.parentId));
      parent?.forEach(item => {
        item.children = _.sortBy(data.filter(o => o.parentId == item.id), "sort");
        treeBuild(data, item.children);
      });
      return parent;
    }

    const data = reactive({
      ctx,
      pctx,
      disabledOptions
    })

    onMounted(() => {
      ctx.loadData()
      pctx.loadData()
    })

    return {
      ...toRefs(data)
    }
  }
})
